package com.yyx.jupiter.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.google.common.hash.Hashing;
import com.yyx.jupiter.entity.AblationExperiment;

import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class AblationUtils {

    public static int getBucketNumber(String hashKey, Integer hashSize) {
        if (hashKey == null || hashKey.isEmpty()) {
            throw new IllegalArgumentException("AB分流hash key不能为空");
        }
        int hash = Hashing.murmur3_32_fixed().hashString(hashKey, StandardCharsets.UTF_8).asInt();
        int positiveHash = Math.abs(hash);
        return positiveHash % hashSize;
    }


    public static String getStrategy(String hashKey, Integer hashSize, JSONObject abtestJson) {
        Integer bucketNumber = getBucketNumber(hashKey, hashSize);
        // TODO: CacheUtils
        Map<String, AblationExperiment> abtestConfigMap = abtestJson.to(new TypeReference<>() {
        });
        List<AblationExperiment> ablationExperiments = new LinkedList<>(abtestConfigMap.values());
        for (AblationExperiment ablationExperiment : ablationExperiments) {
            if (ablationExperiment.getStartNumber() <= bucketNumber && ablationExperiment.getEndNumber() >= bucketNumber) {
                return ablationExperiment.getStrategy();
            }
        }
        return null;
    }
}
